package com.stormragetech.sylwanas.config;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.util.Properties;

/**
 * description: //TODO
 *
 * @author: Xue Bin
 * @version: 1.0.0-SNAPSHOT
 */
public class RabbitConfig {

    private static final String RABBITMQ_IP = "rabbit.ip";
    private static final String RABBITMQ_PORT = "rabbit.port";
    private static final String RABBITMQ_USER = "rabbit.user";
    private static final String RABBITMQ_PASS = "rabbit.pass";

    public static ConnectionFactory factoryInit(String propertiesFile) throws RuntimeException {

        Properties properties = getProperties(propertiesFile);

        if (null == properties.getProperty(RABBITMQ_IP) || properties.getProperty(RABBITMQ_IP).length() <= 0) {
            throw new RuntimeException("the rabbitmq host ip cannot be blank !!!");
        } else if (null == properties.getProperty(RABBITMQ_PORT) || properties.getProperty(RABBITMQ_PORT).length() <= 0) {
            throw new RuntimeException("the rabbitmq host port cannot be blank !!!");
        } else if (null == properties.getProperty(RABBITMQ_USER) || properties.getProperty(RABBITMQ_USER).length() <= 0) {
            throw new RuntimeException("the rabbitmq username cannot be blank !!!");
        } else if (null == properties.getProperty(RABBITMQ_PASS) || properties.getProperty(RABBITMQ_PASS).length() <= 0) {
            throw new RuntimeException("the rabbitmq password cannot be blank !!!");
        }

        String ip = properties.getProperty(RABBITMQ_IP);
        int port = Integer.valueOf(properties.getProperty(RABBITMQ_PORT));
        String userName = properties.getProperty(RABBITMQ_USER);
        String password = properties.getProperty(RABBITMQ_PASS);

        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(ip, port);
        connectionFactory.setUsername(userName);
        connectionFactory.setPassword(password);
        connectionFactory.setPublisherConfirms(true); // enable confirm mode

        return connectionFactory;
    }

    private static Properties getProperties(String propertiesFile) {

        Properties properties = new Properties();
        try {
            Resource res = new ClassPathResource(propertiesFile);
            properties.load(res.getInputStream());
            return properties;
        } catch (IOException e) {
            throw new RuntimeException("Failed to load rabbitmq.properties!");
        }
    }

}
